package com.googlecode.jch.plugin;

import com.googlecode.jch.Solution;
import com.googlecode.jch.SolutionConfig;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.execution.Location;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiClassOwner;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiClassUtil;

import java.util.Iterator;

/**
 * @author Iskander Akishev
 */
public class JCHUtil {
	public static PsiClass getSolutionClass(final Location<?> location) {
		for (Iterator<Location<PsiClass>> iterator = location.getAncestors(PsiClass.class, false); iterator.hasNext();) {
			final Location<PsiClass> classLocation = iterator.next();
			PsiClass clazz = classLocation.getPsiElement();
			if (isSolutionClass(clazz)) return clazz;
		}
		PsiElement element = location.getPsiElement();
		if (element instanceof PsiClassOwner) {
			PsiClass[] classes = ((PsiClassOwner)element).getClasses();
			if (classes.length == 1 && isSolutionClass(classes[0])) return classes[0];
		}
		return null;
	}

	public static boolean isSolutionClass(PsiClass psiClass) {
		PsiClass superClass = psiClass.getSuperClass();
		return (PsiClassUtil.isRunnableClass(psiClass, true, true) &&
				superClass != null && superClass.getQualifiedName().equals(Solution.class.getName()) &&
				AnnotationUtil.isAnnotated(psiClass, SolutionConfig.class.getName(), false)
		);
	}

	public static boolean isInputReaderClass(PsiClass psiClass) {
		return true;
		// todo: implements Closeable, is public, has public constructor from InputStream

//		PsiClass superClass = psiClass.getSuperClass();
//		return (PsiClassUtil.isRunnableClass(psiClass, true, true) &&
//				superClass != null && superClass.getQualifiedName().equals(Solution.class.getName()));
	}

	public static PsiAnnotation getSolutionAnnotation(PsiClass solutionClass) {
		assert isSolutionClass(solutionClass);
		for (PsiAnnotation annotation : solutionClass.getModifierList().getAnnotations()) {
			String annotationFQN = annotation.getQualifiedName();
			if (annotationFQN != null && annotationFQN.equals(SolutionConfig.class.getName())) return annotation;
		}
		return null;
	}
}
